import { Component } from '@angular/core';
import * as Three from 'three';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";

@Component({
  selector: 'app-choose',
  templateUrl: './choose.component.html',
  styleUrls: ['./choose.component.css'],
})
export class ChooseComponent {

  public api = 'http://localhost:2002/choose.html'

  constructor(private router: Router, public http: HttpClient) {
  }
  public name = sessionStorage.getItem("username");
  public tet: any;
  public model: any;
  public color: any;

  ngOnInit() {
    if (sessionStorage.length == 0) {
      alert('请先登录');
      this.router.navigateByUrl('login');
    }

    this.model = sessionStorage.getItem("model");
    this.color = sessionStorage.getItem("color");
    var f: any = document.getElementById('iframeId');
    // 触发子页面的监听事件
    f.contentWindow.postMessage(sessionStorage.getItem("username"), '*');
    window.addEventListener('message', (e) => {
      if (e.data != undefined) {
        this.model = e.data.model;
        this.color = e.data.color;
        sessionStorage.setItem("model", this.model);
        sessionStorage.setItem("color", this.color);
      }
    }, false);
    let name = sessionStorage.getItem("username");
  }

  toIndex() {
    var f: any = document.getElementById('iframeId');
    // 触发子页面的监听事件
    f.contentWindow.postMessage(sessionStorage.getItem("username"), '*');

    // 将选中的模型传给后端
    // 访问接口
    let token: any = sessionStorage.getItem("token");
    let username: any = sessionStorage.getItem("username");

    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': token })
    };

    var api = "http://124.221.112.204:3389/user/model";
    this.http.post(api, { 'username': username, 'model': this.model, 'color': this.color }, httpOptions).subscribe((response: any) => {
      if (response.code == 200) {
        this.router.navigateByUrl('index');

      } else {
      }
    });
  }
}
